package com.zeng.sboot.amqp.consumer.config.amqp;

import com.rabbitmq.client.Channel;
import com.zeng.sboot.demo.amqp.domain.Order;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class OrderReceiver {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "com-route-key.order-receive"),
            exchange = @Exchange(value = "com-exchange"),//"com-exchange",
            key = "com-route-key.*"  // key 指routingKey (key.*  匹配 queue 的key.sss, key.222 等 )
    ))
    @RabbitHandler // 此注解只是标识,标识当前方法如果有消息过来, 消费者要消费的时候调用此方法
    public void onReceived1(@Payload Order order, Channel channel, @Headers Map<String, Object> headers) throws Exception {//@Payload Order order, Channel channel, @Headers Map<String, Object> headers
        System.out.println("==================================================== consumer");
        System.out.println("消费端order: " + order);
        System.out.println(headers);
        //{amqp_receivedDeliveryMode=PERSISTENT,
        // amqp_receivedRoutingKey=com-route-key.*,
        // amqp_contentEncoding=UTF-8,
        // amqp_receivedExchange=com-exchange,
        // amqp_deliveryTag=1,
        // amqp_consumerQueue=com-route-key.order-receive,
        // amqp_redelivered=false,
        // id=56a63af0-ecb4-6dc3-5a90-c95ca125da56,
        // amqp_consumerTag=amq.ctag-hy9hqhMozWcrHqopCG2Jhw,
        // contentType=application/json,
        // __TypeId__=com.zeng.sboot.demo.amqp.domain.Order,
        // timestamp=1591607817547}

        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        // 手工 ACK
        channel.basicAck(deliveryTag, false);
    }
}
